package com.chwn.curiousdiary;

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.multidex.MultiDex;
import android.text.TextUtils;

import com.chwn.curiousdiary.api.ISystemApi;
import com.chwn.curiousdiary.api.IUserApi;
import com.chwn.curiousdiary.api.NetWork;
import com.chwn.curiousdiary.bean.VersionBean;
import com.chwn.curiousdiary.gloable.Constant;
import com.chwn.curiousdiary.gloable.CustomEvent;
import com.chwn.curiousdiary.gloable.User;
import com.chwn.curiousdiary.gloable.UserUtils;
import com.chwn.harulib.mvp.rx.HttpResult;
import com.chwn.harulib.mvp.rx.RxSchedulers;
import com.chwn.harulib.util.NetUtils;
import com.chwn.harulib.util.ToastUtil;
import com.orhanobut.logger.Logger;
import com.squareup.leakcanary.LeakCanary;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;

import java.util.List;

import cn.jpush.android.api.JPushInterface;
import de.greenrobot.event.EventBus;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by Myshikin on 2017/3/20.
 */

public class DiaryApplication extends Application {

    public static DiaryApplication mInstance;

    private User    mUser;
    public  boolean downApp;
    public boolean ISFirst = true;


    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        //TODO 關閉集成测试
        //        MobclickAgent.setDebugMode(true);
        initUmeng();
        initJPush();
        initUser();
        ToastUtil.init(mInstance);
        ToastUtil.setLayoutId(R.layout.toast_custom, R.id.txt_tips);

        initVersionCode();
        initLastVersionCode();

        Logger.init("myshikin");

        LeakCanary.install(this);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    private void initJPush() {
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
    }

    private void initUmeng() {
        // Config.DEBUG = true;
        PlatformConfig.setWeixin("wx8c9a71fed831129c", "f65f5ec9bf2b17adc61b19511395307d");
        PlatformConfig.setQQZone("1105865688", "pJDalAdeJ3G61IJ2");
        UMShareAPI.get(this);
    }

    private void initUser() {
        try {
            mUser = UserUtils.getUser();
            if (mUser == null) {
                return;
            }

            if (!TextUtils.isEmpty(mUser.getUnionid())) {
                login(null, null, 2, mUser.getUnionid(), mUser.getNickName(), mUser.getHeadUrl());
            } else {
                login(mUser.getPhone(), mUser.getPassword(), 1, null, null, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void login(String phone, final String passWord, final int loginWay, final String openId, String nickName, String headUrl) {
        NetWork.getInstance()
                .getApiService(IUserApi.class)
                .userLogin(phone, passWord, loginWay, JPushInterface.getRegistrationID(this), openId, openId, Constant.OSTYPE, nickName, headUrl)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<HttpResult<List<User>>>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(HttpResult<List<User>> userHttpResult) {
                        if (userHttpResult.getResult() == Constant.RESULT_OK) {
                            User user = userHttpResult.getResdata().get(0);
                            user.setPassword(passWord);
                            DiaryApplication.mInstance.saveUser(user);
                            EventBus.getDefault().post(new CustomEvent(CustomEvent.UPDATE_USER_INFO));

                        }
                    }
                });
    }


    public boolean isLogin() {
        return mUser != null && mUser.getUserToken() != null;
    }

    public void saveUser(User user) {
        try {
            UserUtils.saveUser(mInstance, user);
            mUser = UserUtils.getUser();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void loginOut() {
        MobclickAgent.onProfileSignOff();
        try {
            UserUtils.saveUser(mInstance, null);
            mUser = UserUtils.getUser();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public User getmUser() {
        return mUser;
    }

    public int getBabySex() {
        return mUser == null ? 1 : Integer.parseInt(mUser.getBabysex());
    }

    public String getUserToken() {
        if (mUser != null) {
            return mUser.getUserToken();
        }
        return null;
    }

    public int         currentVersionCode;
    public VersionBean versionBean;

    void initVersionCode() {
        PackageManager pm = getPackageManager();//context为当前Activity上下文
        PackageInfo pi = null;
        try {
            pi = pm.getPackageInfo(getPackageName(), 0);
            currentVersionCode = pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }


    private void initLastVersionCode() {

        if (!NetUtils.isNetWorkConnectted(this)) {
            return;
        }
        NetWork.getInstance()
                .getApiService(ISystemApi.class)
                .updateVersion(1, currentVersionCode)
                .compose(RxSchedulers.<HttpResult<VersionBean>>io_main())
                .subscribe(new Action1<HttpResult<VersionBean>>() {
                    @Override
                    public void call(HttpResult<VersionBean> versionBeanHttpResult) {
                        versionBean = versionBeanHttpResult.getResdata();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });
    }

    public void updateCoinCount(int curiosityCount) {
        if (mUser != null) {
            mUser.setCoinCount(curiosityCount + "");
            try {
                UserUtils.saveUser(mInstance, mUser);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
